package org.fhm.zdte.server.api;

import org.fhm.substrate.annotation.BeanInitial;
import org.fhm.substrate.annotation.Component;
import org.fhm.substrate.annotation.Setup;
import org.fhm.substrate.service.LoggerHandler;
import org.fhm.substrate.standard.ILogger;
import org.fhm.zdte.common.ability.IGetIdentification;
import org.fhm.zdte.common.ability.IGetServerAddress;
import org.fhm.zdte.common.constant.protocol.PacketType;
import org.fhm.zdte.common.pojo.Address;
import org.fhm.zdte.common.pool.ThreadPoolFactory;
import org.fhm.zdte.common.service.api.AbstractApi;
import org.fhm.zdte.common.util.CommonUtil;
import org.fhm.zdte.server.config.ServerInitialConfiguration;

import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * API provided by the server side.
 *
 * @author 谭波
 * @since 2023/11/10
 */
@Component
public class ServerApi extends AbstractApi implements IGetIdentification, IGetServerAddress {

    private final ILogger logger = LoggerHandler.getLogger(ServerApi.class);

    @Setup
    private ThreadPoolFactory threadPoolFactory;

    @Setup
    private ServerInitialConfiguration serverInitialConfiguration;

    @Setup
    private CommonUtil commonUtil;

    private String identification;

    /**
     * Enable the heart beat detection of the server side.
     */
    @SuppressWarnings("unused")
    public void onlineCheck() {
        threadPoolFactory.submitPeriodicTask(
                () ->
                        sendDealTask.getTaskAndSubmit(
                                abstractMessageWrappers.getMessageByPacketType(
                                        PacketType.ONLINE_CHECK,
                                        null, identification,
                                        "", "",
                                        null, null, null,
                                        null
                                ),
                                null
                        ),
                serverInitialConfiguration.getOnlineCheckSchedule(),
                TimeUnit.SECONDS
        );
    }

    @BeanInitial
    private void beanInitial() {
        identification = commonUtil.getIdentification(new HashSet<>());
        logger.info("server identity is {}", identification);
    }

    @Override
    public String getIdentification() {
        return identification;
    }

    @Override
    public Address getServerAddress() {
        return null;
    }
}
